import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/constants.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/book/BookSearchDto.dart';
import 'package:ichinesereader/models/class/ClassDetailsNew.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/grids/bookGridWithCheckBoxTeaching.dart';
import 'package:ichinesereader/widgets/buttons/floatingActionButtonAddBooksToFolder.dart';

// ignore: must_be_immutable
class CoreMaterialBooksTabPage extends StatefulWidget {
  CoreMaterialBooksTabPage({
    Key? key,
    this.programId,
  }) : super(key: key);

  String? programId;

  CoreMaterialBooksTabPageState createState() =>
      new CoreMaterialBooksTabPageState();
}

class CoreMaterialBooksTabPageState extends State<CoreMaterialBooksTabPage> {
  final box = Hive.box('appconfig');
  final BooksController _controller = Get.find();
  String? _selectedSubProgramId;
  List<Tree> programTree = [];
  List<Tree> subProgramTree = [];
  List<Tree> subsubProgramTree = [];
  int limit = 20;
  int selectedPageNumber = 1;
  BookSearchDto dto = new BookSearchDto();
  String? currentClassProgramId = '';
  String? currentSelectdProgramId = '';
  var cdn = ClassDetailsNew();
  int selectedThemeOption = 0;

  void searchThemedBooks(String query) {
    dto.query = query;
    selectedPageNumber = 1;
    _controller.fetchProgramThemeBookItems(limit, selectedPageNumber - 1, dto);
  }

  void initState() {
    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    _controller.themedBookItems.clear();
    String _classDetails =
        box.get(CacheManagerKey['currentclassdetails'].toString()) ?? '';
    currentClassProgramId =
        box.get(CacheManagerKey['currentclassProgramId'].toString());

    if (_classDetails != '') {
      cdn = classDetailsNewFromJson(_classDetails);
      programTree = cdn.program?.tree!.lowerProgram
          ?.where((element) => element.id == currentClassProgramId)
          .first
          .lowerProgram as List<Tree>;
    }

    if (programTree.isNotEmpty && widget.programId != null) {
      subProgramTree = programTree
          .where((element) => element.id == widget.programId)
          .first
          .lowerProgram as List<Tree>;

      if (subProgramTree.isNotEmpty) {
        currentSelectdProgramId = subProgramTree[0].id.toString();

        if (subProgramTree[0].lowerProgram != null &&
            subProgramTree[0].lowerProgram!.isNotEmpty) {
          subsubProgramTree = subProgramTree[0].lowerProgram as List<Tree>;
        }
      }
    }

    Future.delayed(Duration(milliseconds: 50), () {
      if (isTeacher) {
        try {
          if (currentSelectdProgramId != '') {
            dto.programKind = [];
            if (currentSelectdProgramId != '') {
              dto.programKind?.add(currentSelectdProgramId.toString());
            } else {
              dto.programKind?.add(widget.programId.toString());
            }
            _controller.fetchProgramThemeBookItems(Constants.pageLimit, 0, dto);
          } else {}
        } catch (error) {
          Log.debug(error);
        }
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _controller.selectedThemedBookItems.clear();
    _controller.themedBookItems.clear();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build CoreMaterialBooksTabPage');

    final isBigScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenBigSize;
    final isMediumScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenMediumSize;
    // final isSmallScreen =
    //     MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;
    return Scaffold(
        backgroundColor: Colors.transparent,
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            isMediumScreen
                ? Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Visibility(
                          visible: subProgramTree.isNotEmpty,
                          child: Padding(
                            padding: const EdgeInsets.only(right: 12.0),
                            child: DropdownButtonFormField(
                                dropdownColor: Get.isDarkMode
                                    ? AppTheme.colors.darkTheme2
                                    : Get.theme.primaryColor,
                                isExpanded: true,
                                value: subProgramTree[0],
                                decoration: InputDecoration(
                                  contentPadding: EdgeInsets.only(
                                      left: 15.0, top: 9.0, bottom: 9.0),
                                  labelStyle: TextStyle(
                                      color: Get.isDarkMode
                                          ? Get.theme.primaryColorDark
                                          : Colors.black),
                                  labelText: 'Themes'.tr,
                                ),
                                items: subProgramTree
                                    .map((program) => DropdownMenuItem(
                                          value: program,
                                          child: Text(
                                            program.name.toString(),
                                            style: TextStyle(
                                                fontSize: 15.0,
                                                color: Get.isDarkMode
                                                    ? Get.theme.primaryColorDark
                                                    : Colors.white),
                                            overflow: TextOverflow.fade,
                                            softWrap: true,
                                          ),
                                        ))
                                    .toList(),
                                onChanged: (value) {
                                  var item = value as Tree;

                                  if (item.id != null) {
                                    _selectedSubProgramId = item.id.toString();

                                    dto = new BookSearchDto();
                                    dto.programKind = [];
                                    dto.programKind?.add(item.id.toString());
                                    _controller.selectedThemedBookItemsClear();
                                    _controller.themedBookItems.clear();
                                    selectedPageNumber = 1;
                                    _controller.fetchProgramThemeBookItems(
                                        limit, selectedPageNumber - 1, dto);

                                    setState(() {
                                      subsubProgramTree = subProgramTree
                                          .where((element) =>
                                              element.id ==
                                              _selectedSubProgramId)
                                          .first
                                          .lowerProgram as List<Tree>;
                                    });
                                  }
                                }),
                          )),
                      Visibility(
                        visible: subsubProgramTree.isNotEmpty,
                        child: Container(
                          height: 30.0,
                          margin: EdgeInsets.symmetric(vertical: 9.0),
                          child: ListView.builder(
                            itemCount: subsubProgramTree.length,
                            scrollDirection: Axis.horizontal,
                            itemBuilder: ((context, index) {
                              return Padding(
                                padding:
                                    const EdgeInsets.symmetric(horizontal: 3.0),
                                child: ChoiceChip(
                                  selectedColor: Get.isDarkMode
                                      ? Colors.white
                                      : AppTheme.colors.orangeBtn,
                                  backgroundColor: Get.isDarkMode
                                      ? Get.theme.primaryColor
                                      : Colors.grey[400],
                                  shape: BeveledRectangleBorder(
                                    side: BorderSide(
                                        color: Get.isDarkMode
                                            ? Colors.black
                                            : Colors.white,
                                        width: 0.3),
                                    borderRadius: BorderRadius.circular(1.0),
                                  ),
                                  selected: selectedThemeOption == index,
                                  onSelected: (selected) {
                                    setState(() {
                                      selectedThemeOption =
                                          selected ? index : 0;
                                    });
                                    //if (value == false) return;
                                    var subprogram = subsubProgramTree[index];
                                    // BookSearchDto dto =
                                    //     new BookSearchDto();
                                    dto = new BookSearchDto();
                                    dto.programKind = [];
                                    dto.programKind
                                        ?.add(subprogram.id.toString());
                                    // _controller.selectedThemedBookItems
                                    //     .clear();
                                    // _controller.themedBookItems.clear();
                                    _controller.selectedThemedBookItemsClear();
                                    _controller.themedBookItems.clear();
                                    selectedPageNumber = 1;
                                    _controller.fetchProgramThemeBookItems(
                                        limit, selectedPageNumber - 1, dto);
                                  },
                                  label: Text(
                                    subsubProgramTree[index].name.toString(),
                                    style: TextStyle(
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Colors.white,
                                      letterSpacing: 1,
                                    ),
                                  ),
                                ),
                              );
                            }),
                          ),
                        ),
                      ),
                    ],
                  )
                : Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Visibility(
                          visible: subProgramTree.isNotEmpty,
                          child: Expanded(
                            flex: isBigScreen ? 3 : 2,
                            child: Padding(
                              padding: const EdgeInsets.only(right: 12.0),
                              child: DropdownButtonFormField(
                                  dropdownColor: Get.isDarkMode
                                      ? AppTheme.colors.darkTheme2
                                      : Get.theme.primaryColor,
                                  isExpanded: true,
                                  value: subProgramTree[0],
                                  decoration: InputDecoration(
                                    contentPadding: EdgeInsets.only(
                                        left: 15.0, top: 9.0, bottom: 9.0),
                                    labelStyle: TextStyle(
                                        color: Get.isDarkMode
                                            ? Get.theme.primaryColorDark
                                            : Colors.black),
                                    labelText: 'Themes'.tr,
                                  ),
                                  items: subProgramTree
                                      .map((program) => DropdownMenuItem(
                                            value: program,
                                            child: Text(
                                              program.name.toString(),
                                              style: TextStyle(
                                                  fontSize: 15.0,
                                                  color: Get.isDarkMode
                                                      ? Get.theme
                                                          .primaryColorDark
                                                      : Colors.white),
                                              overflow: TextOverflow.fade,
                                              softWrap: true,
                                            ),
                                          ))
                                      .toList(),
                                  onChanged: (value) {
                                    var item = value as Tree;

                                    if (item.id != null) {
                                      _selectedSubProgramId =
                                          item.id.toString();

                                      dto = new BookSearchDto();
                                      dto.programKind = [];
                                      dto.programKind?.add(item.id.toString());
                                      _controller
                                          .selectedThemedBookItemsClear();
                                      _controller.themedBookItems.clear();
                                      selectedPageNumber = 1;
                                      _controller.fetchProgramThemeBookItems(
                                          limit, selectedPageNumber - 1, dto);

                                      setState(() {
                                        subsubProgramTree = subProgramTree
                                            .where((element) =>
                                                element.id ==
                                                _selectedSubProgramId)
                                            .first
                                            .lowerProgram as List<Tree>;
                                      });
                                    }
                                  }),
                            ),
                          )),
                      Visibility(
                        visible: subsubProgramTree.isNotEmpty,
                        child: Expanded(
                          flex: isBigScreen ? 7 : 8,
                          child: Container(
                            height: 30.0,
                            child: ListView.builder(
                              itemCount: subsubProgramTree.length,
                              scrollDirection: Axis.horizontal,
                              itemBuilder: ((context, index) {
                                return Padding(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 4.0),
                                  child: ChoiceChip(
                                    selectedColor: Get.isDarkMode
                                        ? Colors.white
                                        : AppTheme.colors.orangeBtn,
                                    backgroundColor: Get.isDarkMode
                                        ? Get.theme.primaryColor
                                        : Colors.grey[400],
                                    shape: BeveledRectangleBorder(
                                      side: BorderSide(
                                          color: Get.isDarkMode
                                              ? Colors.black
                                              : Colors.white,
                                          width: 0.3),
                                      borderRadius: BorderRadius.circular(1.0),
                                    ),
                                    selected: selectedThemeOption == index,
                                    onSelected: (selected) {
                                      setState(() {
                                        selectedThemeOption =
                                            selected ? index : 0;
                                      });
                                      //if (value == false) return;
                                      var subprogram = subsubProgramTree[index];
                                      // BookSearchDto dto =
                                      //     new BookSearchDto();
                                      dto = new BookSearchDto();
                                      dto.programKind = [];
                                      dto.programKind
                                          ?.add(subprogram.id.toString());
                                      // _controller.selectedThemedBookItems
                                      //     .clear();
                                      // _controller.themedBookItems.clear();
                                      _controller
                                          .selectedThemedBookItemsClear();
                                      _controller.themedBookItems.clear();
                                      selectedPageNumber = 1;
                                      _controller.fetchProgramThemeBookItems(
                                          limit, selectedPageNumber - 1, dto);
                                    },
                                    label: Text(
                                      subsubProgramTree[index].name.toString(),
                                      style: TextStyle(
                                        color: Get.isDarkMode
                                            ? Colors.black
                                            : Colors.white,
                                        letterSpacing: 1,
                                      ),
                                    ),
                                  ),
                                );
                              }),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
            Flexible(
                child: _controller.obx(
              (data) => BookGridWithCheckBoxTeaching(
                books: _controller.themedBookItems,
                readingType: NanhaiBookReadingTypes.theme,
              ),
              onLoading: Container(),
              onError: ((error) => Center(child: Text('Coming soon ...'.tr))),
              onEmpty: Center(child: Text('Coming soon ...'.tr)),
            )),
            // _controller.obx(
            //   (data) => NumberPagination(
            //     onPageChanged: (int pageNumber) {
            //       setState(() {
            //         selectedPageNumber = pageNumber;
            //         _controller.fetchProgramThemeBookItems(
            //             limit, selectedPageNumber - 1, dto);
            //       });
            //     },
            //     pageTotal: _controller.themedBooksTotalNum.value % limit == 0
            //         ? (_controller.themedBooksTotalNum.value ~/ limit).toInt()
            //         : (_controller.themedBooksTotalNum.value ~/ limit).toInt() +
            //             1,
            //     threshold: 5,
            //     pageInit: selectedPageNumber,
            //     // picked number when init page
            //     colorPrimary: Theme.of(context).primaryColorLight,
            //     colorSub: Theme.of(context).primaryColorDark,
            //   ),
            // ),
          ],
        ),
        floatingActionButton: FloatingActionButtonAddBookToFolder(
          readingType: NanhaiBookReadingTypes.theme,
        ));
  }
}
